import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/screens/my/role_edit_screen.dart';

class RoleManagementScreen extends ConsumerStatefulWidget {
  const RoleManagementScreen({super.key});

  @override
  ConsumerState<RoleManagementScreen> createState() => _RoleManagementScreenState();
}

class _RoleManagementScreenState extends ConsumerState<RoleManagementScreen> {
  late Future<List<Map<String, dynamic>>> _futureRoles;

  @override
  void initState() {
    super.initState();
    _futureRoles = _load();
  }

  Future<List<Map<String, dynamic>>> _load() async {
    return await ref.read(roleServiceProvider).fetchRoles();
  }

  Future<void> _showCreateDialog() async {
    final nameController = TextEditingController();
    final ok = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('新增角色'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(labelText: '角色名称'),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),
          ElevatedButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定')),
        ],
      ),
    );
    if (ok == true && nameController.text.trim().isNotEmpty) {
      await ref.read(roleServiceProvider).createRole(name: nameController.text.trim());
      setState(() {
        _futureRoles = _load();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('角色管理')),
      body: FutureBuilder<List<Map<String, dynamic>>>(
        future: _futureRoles,
        builder: (ctx, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('加载失败: ${snapshot.error}'));
          }
          final roles = snapshot.data ?? [];
          if (roles.isEmpty) {
            return const Center(child: Text('暂无角色'));
          }
          return ListView.builder(
            itemCount: roles.length,
            itemBuilder: (ctx, idx) {
              final r = roles[idx];
              return ListTile(
                title: Text(r['name'] ?? ''),
                subtitle: Text('ID: ${r['id']}'),
                trailing: IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () async {
                    await ref.read(roleServiceProvider).deleteRole(r['id'] as int);
                    setState(() {
                      _futureRoles = _load();
                    });
                  },
                ),
                onTap: () async {
                  final refreshed = await Navigator.push<bool>(context, MaterialPageRoute(builder: (_) => RoleEditScreen(role: r)));
                  if (refreshed == true) {
                    setState(() {_futureRoles=_load();});
                  }
                },
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showCreateDialog,
        child: const Icon(Icons.add),
      ),
    );
  }
} 